package GitObjController

import (
	"arabApi/app/api/controllers"
	"arabApi/app/api/controllers/CFun"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/CRequest"
	"arabApi/app/api/requests/ObjGitRequest"
	"arabApi/app/api/services/ObjGitService"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
)

type GitObjBranch struct {
	controllers.BaseAPIController
}

func (r GitObjBranch) List(c *gin.Context) {

	objreq := ObjGitRequest.GitBranch{}
	if err := c.ShouldBindQuery(&objreq); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("解析错误"+err.Error()))
		return
	}

	data := gin.H{}
	data["list"], data["count"] = ObjGitService.BranchList(objreq)

	CFun.Ajax_return_success(c, CFun.WithData(data))

}

func (r GitObjBranch) MsgById(c *gin.Context) {
	id := CRequest.Oid{}

	if err := c.ShouldBindQuery(&id); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("未找到对应的ID"+err.Error()))
		return
	}
	if ok := requests.Validate(c, &id, CRequest.CheckID); !ok {
		return
	}
	msg := ObjGitService.BranchMsgByID(id.Id)

	data := gin.H{}
	data["msg"] = msg
	obj := ObjGitService.MsgByID(cast.ToString(msg.ObId))

	if err, s := checkDiff1(obj.JobPath, msg.Branch); err == nil {
		data["data"] = ex_table(s)
	}

	CFun.Ajax_return_success(c, CFun.WithData(data))
}

func (r GitObjBranch) Edit(c *gin.Context) {

	s := ObjGitRequest.GitBranch{}
	if err := c.ShouldBindBodyWith(&s, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("未找到对应的ID"+err.Error()))
		return
	}
	if ok := requests.Validate(c, &s, ObjGitRequest.CheckGitObjBranch); !ok {
		return
	}

	if err := ObjGitService.BranchEdit(s); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("编辑失败"+err.Error()))
	} else {
		CFun.Ajax_return_success(c)
	}

}

func (r GitObjBranch) Add(c *gin.Context) {

	s := ObjGitRequest.GitBranch{}
	if err := c.ShouldBindBodyWith(&s, binding.JSON); err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("未找到对应的ID"+err.Error()))
		return
	}
	if ok := requests.Validate(c, &s, ObjGitRequest.CheckGitObjBranch); !ok {
		return
	}

	id, err := ObjGitService.BranchAdd(s)
	if err != nil {
		CFun.Ajax_return_fail(c, CFun.WithMsg("添加失败"+err.Error()))
		return
	}

	msg := ObjGitService.BranchMsgByID(cast.ToString(id))
	barch := msg.Branch

	objPathStruct := ObjGitService.MsgByID(cast.ToString(msg.ObId))
	objPath := objPathStruct.JobPath
	if code, msg1 := NewBranch(barch, cast.ToString(id), objPath); code != false {
		if err := ObjGitService.EditBranchStep(cast.ToString(id), 1); err == nil {
			CFun.Ajax_return_success(c, CFun.WithData(id), CFun.WithMsg("添加成功"))
			return
		}

		CFun.Ajax_return_fail(c, CFun.WithMsg("添加失败1"+msg1))
	} else {
		CFun.Ajax_return_fail(c, CFun.WithMsg("添加失败2"+msg1))
	}

}
